<script lang="ts" setup>
import { ref, computed, onMounted, reactive } from 'vue'
import PageContainer from '@/components/PageContainer.vue'
import { useProjectStore } from '@/stores'
import {
  getPromotingBtnColor,
  mapProjectFromBackend,
  Project,
  ProjectFromBackend,
} from '@/types/project'
import { ProjectDelectStatus } from '@/utils/enum'
import projectApi from '@/api/project'
import { ElMessageBox, ElMessage, ElDialog } from 'element-plus'

const projectStore = useProjectStore()

interface projectSelection {
  pageSize: number
  pageNum: number
  total: number
}

const projectSelection = reactive<projectSelection>({
  pageSize: 10,
  pageNum: 1,
  total: 0,
})
onMounted(async () => {
  projectSelection.total = await projectStore.fetchProjects(projectSelection)
})
const projectType = ref([
  '所有在线项目',
  '需邮件推广',
  '已推广项目',
  '标记项目',
  '未审核项目',
])

// 添加项目类型切换处理
const handleProjectTypeChange = async (val: number) => {
  projectTypeOption.value = val
  // 重置到第一页
  projectSelection.pageNum = 1
  projectSelection.total = await projectStore.fetchProjects(projectSelection)
}

const projectTypeOption = ref(0)
const projectInfoLabels = ref([
  { label: '项目名称', prop: 'name' },
  { label: '项目简介', prop: 'description' },
  { label: '发布时间', prop: 'createdAt' },
  { label: '项目详情', prop: 'details' },
  { label: '项目审批', prop: 'approval' },
  { label: '操作', prop: 'action' },
  { label: '项目偏向', prop: 'projectFocus' },
  { label: '标记状态', prop: 'marked' },
  { label: '需要推广', prop: 'promotionEnabled' },
  { label: '推广状态', prop: 'promotionStatusLabel' },
  { label: '跨校合作', prop: 'isCrossSchool' },
  { label: '团队人数', prop: 'teamSize' },
  { label: '发起学校', prop: 'initiatingSchool' },
  { label: '学校要求', prop: 'schoolRequirements' },
  { label: '详细要求', prop: 'detailedRequirements' },
  { label: '允许积极学生参与', prop: 'allowPositiveStudents' },
  { label: '发起人邮箱', prop: 'email' },
  { label: '发起人电话', prop: 'phone' },
  { label: '项目ID', prop: 'id' },
])
const tmpMemberCount = ref<number>(null)

// 修改团队人数
async function changeMemberCount() {
  if (!currentProject.value || tmpMemberCount.value === null) {
    ElMessage.error('请先选择项目并输入人数')
    return
  }

  if (tmpMemberCount.value <= 0) {
    ElMessage.error('团队人数必须大于0')
    return
  }

  try {
    projectApi.setMemberCountService({
      id: currentProject.value.id,
      memberCount: tmpMemberCount.value,
    })

    ElMessageBox.alert('修改成功')
    // 更新当前项目的团队人数
    currentProject.value.teamSize = tmpMemberCount.value
    tmpMemberCount.value = null
    // 重新加载项目列表以更新显示
    projectSelection.total = await projectStore.fetchProjects(projectSelection)
  } catch (error: any) {
    console.error('修改团队人数失败:', error)
    ElMessage.error('修改失败:' + error.message)
  }
}

const projects = computed<Project[]>(() => {
  const backendResponse: ProjectFromBackend[] = projectStore.getProjects()
  return backendResponse.map((element) => mapProjectFromBackend(element))
})
const detailVisible = ref(false)
const currentProject = ref<Project | null>(null)
const showDetail = (project: Project) => {
  currentProject.value = project
  detailVisible.value = true
}
const promoteProject = (project: Project) => {
  project.promotionEnabled = true
  console.log(`项目 ${project.name} 已推广`)
}

async function markProject(project: Project) {
  try {
    let result: any
    if (project.marked) {
      result = await projectApi.unmarkProjectService(project.id)
    } else {
      result = await projectApi.markProjectService(project.id)
    }
  } catch (e) {
    console.error('标记项目失败:', e)
    ElMessageBox.alert(e.message, {
      type: 'error',
    })
  }
  project.marked = !project.marked
}
const filteredProjects = computed(() => {
  switch (projectTypeOption.value) {
    case 0:
      return projects.value
    case 1:
      return projects.value.filter((p) => p.promotionEnabled)
    case 2:
      return projects.value.filter(
        (p) => p.promotionStatus === ProjectDelectStatus.PROMOTION,
      )
    case 3:
      return projects.value.filter((p) => p.marked)
    default:
      return projects.value // 修复：默认返回所有项目而不是null
  }
})
// 删除相关功能
const deleteDialogVisible = ref(false)
const currentDeleteProject = ref<Project | null>(null)

// 打开删除确认对话框
const openDeleteDialog = (project: Project) => {
  currentDeleteProject.value = project
  deleteDialogVisible.value = true
}

// 执行删除操作
async function deleteProject() {
  if (!currentDeleteProject.value) {
    ElMessage.error('请选择要删除的项目')
    return
  }

  try {
    const res = await projectApi.deleteProjectService(
      currentDeleteProject.value.id,
    )
    if (res.data.code === 200) {
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      // 重新加载项目列表
      projectSelection.total =
        await projectStore.fetchProjects(projectSelection)
    } else {
      ElMessage.error('删除失败:' + res.data.msg)
    }
  } catch (error: any) {
    console.error('删除项目失败:', error)
    ElMessage.error('删除失败:' + error.message)
  }
}

async function handleCurrentChange(pageNum: number) {
  projectSelection.pageNum = pageNum
  projectSelection.total = await projectStore.fetchProjects(projectSelection)
}

async function handleSizeChange(pageSize: number) {
  projectSelection.pageSize = pageSize
  projectSelection.pageNum = 1 // 重置到第一页
  projectSelection.total = await projectStore.fetchProjects(projectSelection)
}

// 审核相关功能
const auditDialogVisible = ref(false)
const currentAuditProject = ref<Project | null>(null)
const auditForm = ref({
  projectId: null as number | null,
  auditStatus: true,
  remark: '',
})

// 打开审核对话框
const openAuditDialog = (project: Project) => {
  currentAuditProject.value = project
  auditForm.value.projectId = project.id
  auditForm.value.auditStatus = true
  auditForm.value.remark = ''
  auditDialogVisible.value = true
}

// 提交审核结果
async function submitAudit() {
  if (!auditForm.value.projectId) {
    ElMessage.error('项目ID不能为空')
    return
  }

  try {
    let res = await projectApi.updateAuditStatusService({
      projectId: auditForm.value.projectId,
      auditStatus: auditForm.value.auditStatus,
      remark: auditForm.value.remark,
    })
    console.log('qingqiu===============')
    console.log(res)
    if (res.data.code === 200) {
      ElMessage.success('审核成功')
      auditDialogVisible.value = false
      // 重新加载项目列表以更新审核状态
      projectSelection.total =
        await projectStore.fetchProjects(projectSelection)
    } else {
      ElMessage.error('审核失败:' + res.data.msg)
    }
  } catch (error: any) {
    ElMessage.error('审核失败:' + error.message)
  }
}
</script>

<template>
  <page-container title="在线项目管理">
    <template #extra>
      <el-select
        v-model="projectTypeOption"
        placeholder="项目类型"
        class="project-type-select"
        @change="handleProjectTypeChange"
      >
        <el-option
          v-for="(type, idx) in projectType"
          :key="idx"
          :label="type"
          :value="idx"
        />
      </el-select>
    </template>

    <!-- 项目列表内容 -->
    <el-table :data="filteredProjects" class="project-table">
      <el-table-column
        v-for="item in projectInfoLabels.slice(0, 6)"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
      >
        <!-- 详情弹出框 - 只在描述列显示详情按钮 -->
        <template v-if="item.prop === 'details'" #default="{ row }">
          <el-button type="text" @click="showDetail(row)"> 查看详情</el-button>
        </template>

        <!-- 项目审批列 -->
        <template v-else-if="item.prop === 'approval'" #default="{ row }">
          <div
            v-if="
              row.auditStatus === null ||
              row.auditStatus === undefined ||
              row.auditStatus == 0
            "
          >
            <el-button
              size="small"
              type="warning"
              @click="openAuditDialog(row)"
            >
              待审核
            </el-button>
          </div>
          <div v-else-if="row.auditStatus == 1">
            <el-tag type="success">审核通过</el-tag>
          </div>
          <div v-else>
            <el-popover
              placement="top-start"
              title="审核不通过原因"
              :width="200"
              trigger="hover"
              :content="row.auditRemark || '无具体原因'"
            >
              <template #reference>
                <el-tag type="danger">审核不通过</el-tag>
              </template>
            </el-popover>
          </div>
        </template>

        <!-- 操作列 -->
        <template v-else-if="item.prop === 'action'" #default="{ row }">
          <el-button
            size="small"
            :type="
              getPromotingBtnColor(row.promotionStatus, row.promotionEnabled)
            "
            @click="promoteProject(row)"
          >
            {{ row.promotionStatusLabel }}
          </el-button>
          <el-button
            size="small"
            :type="row.marked ? 'success' : 'warning'"
            @click="markProject(row)"
          >
            {{ row.marked ? '已标记' : '标记' }}
          </el-button>
          <el-button size="small" type="danger" @click="openDeleteDialog(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="projectSelection.pageNum"
      v-model:page-size="projectSelection.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="projectSelection.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" width="50%">
      <div v-if="currentProject">
        <el-descriptions title="项目详细信息" :column="2">
          <el-descriptions-item
            v-for="item in projectInfoLabels"
            :key="item.prop"
            :label="item.label"
          >
            <span v-if="typeof currentProject[item.prop] === 'boolean'">{{
              currentProject[item.prop] ? '是' : '否'
            }}</span>
            <div v-else-if="item.prop === 'teamSize'">
              <span>{{ currentProject[item.prop] || '无' }}</span>
              <el-input
                type="number"
                v-model="tmpMemberCount"
                placeholder="修改人数"
              ></el-input>
              <el-button @click="changeMemberCount">提交</el-button>
            </div>
            <span v-else>{{ currentProject[item.prop] || '无' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="项目审核" width="500">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="项目名称">
          <span>{{ currentAuditProject?.name }}</span>
        </el-form-item>
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="auditForm.auditStatus === false" label="不通过原因">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            placeholder="请输入不通过的原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!--项目删除对话框-->
    <el-dialog v-model="deleteDialogVisible" title="删除项目">
      <div v-if="currentDeleteProject">
        <p>
          确定要删除项目 "<strong>{{ currentDeleteProject.name }}</strong
          >" 吗？
        </p>
        <p>此操作不可恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteProject">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </page-container>
</template>

<style lang="css" scoped>
.project-type-select {
  width: 200px;
}

.project-table {
  width: 100%;
}
</style>
